package site.hanzhe.controller;
/**
 * 角色管理的Controller
 */

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import site.hanzhe.constant.CrowdConstant;
import site.hanzhe.entity.RoleEntity;
import site.hanzhe.service.RoleService;
import site.hanzhe.utils.R;

import java.lang.reflect.Type;
import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    // 访问首页获取角色列表
    @GetMapping("/get/page/info.json")
    @PreAuthorize("hasAuthority('role:get')")
    public R getPageInfo(
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam(value = "size", defaultValue = CrowdConstant.PAGE_LIST_SIZE) Integer size,
            @RequestParam(value = "query", defaultValue = "") String query,
            Model model){
        return R.success("获取角色列表成功！").setAttribute("info", roleService.selectPageInfo(current, size, query));
    }

    // 添加角色
    @PostMapping("/insert.json")
    @PreAuthorize("hasAuthority('role:add')")
    public R insertRole(String name){
        return R.success("角色【" + name + "】添加成功！").setAttribute("count", roleService.insertRole(name));
    }

    // 编辑角色
    @PostMapping("/update.json")
    @PreAuthorize("hasAuthority('role:edit')")
    public R updateRole(RoleEntity entity){
        return R.success("角色编辑成功！").setAttribute("count", roleService.updateRole(entity));
    }

    // 删除角色(单个和批量统一处理)
    @PostMapping("/delete/list/by/id.json")
    @PreAuthorize("hasAuthority('role:delete')")
    public R deleteRoleByIdList(String listId){
        String msg = null;
        // 创建具有泛型的List的Type对象
        Type type = new TypeToken<List<String>>(){}.getType();
        // 通过Type对象进行JSON转换
        List<String> list = new Gson().fromJson(listId, type);
        int count = roleService.deleteRoleByIdList(list);
        if ( list.size() == 1 && count == 1 ) {
            msg = "角色删除成功！";
        } else if ( list.size() != count ) {
            msg = "成功删除" + count + "条角色信息，失败了" + (list.size() - count) + "条";
        } else {
            msg = "成功删除" + count + "条角色信息";
        }
        return R.success(msg);
    }

}